<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Class : Login_model (Login Model)
 * Login model class to get to authenticate user credentials 
 * @author : Kishor Mali
 * @version : 1.1
 * @since : 15 November 2016
 */
class AmazonOrder_model extends CI_Model
{
    function getOrders($page, $segment) {
    	$this->db->select('BaseTbl.id, BaseTbl.order_name, BaseTbl.createdDtm, BaseTbl.created, BaseTbl.remark, BaseTbl.created, Users.name as createdBy, Count(Details.id) as details_count');
        $this->db->from('tbl_amazon_order as BaseTbl');
        $this->db->join('tbl_users as Users','Users.userId = BaseTbl.created');
        $this->db->join('tbl_amazon_order_details as Details','Details.order_id = BaseTbl.id');
        $this->db->order_by('BaseTbl.createdDtm', 'DESC');
        $this->db->group_by('Details.order_id', 'DESC');

        $this->db->limit($page, $segment);
        $query = $this->db->get();
        
        $result = $query->result();   
        return $result;
    }

    function getOrder($id) {
    	$this->db->select('BaseTbl.id, BaseTbl.order_name, BaseTbl.createdDtm, BaseTbl.created, BaseTbl.remark');
        $this->db->from('tbl_amazon_order as BaseTbl');
        $this->db->where('BaseTbl.id', $id);
        $this->db->order_by('BaseTbl.createdDtm', 'DESC');
        $query = $this->db->get();
        $order = $query->row();
        $order->details = $this->getOrderDetails($id);
        return $order;
    }

    function countOrderDetails($id) {
    	$this->db->select('*');
        $this->db->from('tbl_amazon_order_details as BaseTbl');
        $this->db->where('BaseTbl.order_id', $id);
        return $this->db->count_all_results();
    }

    function getOrderDetails($id) {
    	$this->db->select('*');
        $this->db->from('tbl_amazon_order_details as BaseTbl');
        $this->db->where('BaseTbl.order_id', $id);
        $this->db->order_by('BaseTbl.createdDtm', 'DESC');
        $query = $this->db->get();
        $result = $query->result();
        return $result;
    }

    function createOrder($order) {
    	$this->db->trans_start();
    	$data = array (
    		'id' => null,
    		'order_name' => time(),
    		'created' => $this->session->userdata ( 'userId' ),
    		'remark' => 'First Order'
    	);
    	$this->db->insert('tbl_amazon_order', $data);
    	$order_id = $this->db->insert_id();
    	

    	$details = $order['details'];

    	foreach ($details as $key => $order_detail) {
    		$details[$key]['order_id'] = $order_id;
    		$details[$key]['id'] = null;
    	}

    	$this->db->insert_batch('tbl_amazon_order_details', $details);
    	$this->db->trans_complete();
    }

    function deleteOrder($id) {
    	$this->db->where('id', $id);
        $this->db->delete('tbl_amazon_order');
        return TRUE;

    }
}

?>